<template>
  <div v-for="(item, index) in compList"
    :key="index"
  >
    <Teleport :to="'#' + item.id" :disabled="moveDisabled">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>
              {{item.title}} &nbsp; &nbsp; 
            </span>
          </div>
        </template>
        <component
          :is="comp[item.key]"
          v-bind="item.props"
        >
        </component>
      </el-card>
    </Teleport>

  </div>
</template>

<script>
  import { watch, ref, reactive } from 'vue'
  import { ElCard } from 'element-plus'
  import { store } from '@naturefw/nf-state'

  const getDiv = (comp) => {
    const keys = Object.keys(comp)
    const re = []
    const arr1 = document.getElementsByClassName('v-md-editor-preview')
    const arr2 = arr1[0].getElementsByTagName('div')
    const arr = Array.from(arr2)
    arr.forEach(div => {
      const key = div.getAttribute("data-key")
      if (key) {
        if (keys.includes(key)){
          const props2 = div.getAttribute("data-props")
          const title = div.getAttribute("data-title") ?? '没有标题'
          const props = (props2) ? JSON.parse(props2) : {}
          re.push({
            id: div.id,
            key,
            props,
            title
          })
          div.innerHTML = ''
        }
      }
    })

    return re
  }
</script>

<script setup>
  const props = defineProps({
    doc: Object
  })

  const { comp, current } = store

  // 要加载的组件列表
  const compList = reactive([])
  
  // 是否移动
  const moveDisabled = ref(true)

  watch(() => current.menuInfo.menuId, (id) => {
    if (id) {
      compList.length = 0
      moveDisabled.value = true
      setTimeout(() => {
        const compKeys = getDiv(comp)
        // console.log(compKeys)
        if (compKeys.length > 0) {
          compList.push(...compKeys)
          moveDisabled.value = false
        }
      }, 500)
    }
  }, {immediate: true})
  
</script>